
from random import sample
from .models import QuestionType,Question

class CreatePaper():
    '''
    功能：随机生成试卷题目
    dict_arg:是'paper/'提交的request.POST字典
    
    例子：{'question_type1':['问题类型ID','数量','分值']}
    
    self.info_dict:随机生成试题信息字典，
    例子：{'英汉互译题': [<Question: 7.    When do you get up everyday ?>,
    <Question: 4.teacher(     ) computer (       )>, <Question: try (     )>] }

    self.info_dict_pk()：将info_dict的值转变成pk值
    '''
    
    def __init__(self,dict_arg):
        self.dict_arg = dict_arg
        self.info_dict = self.info_dict_obj()
    def info_dict_obj(self):
        info_dict = {}
        for key,info in self.dict_arg.items():
            if info[0] != '' and not key.startswith('csrf') and not key.startswith('paper'):
                question_obj = QuestionType.objects.get(question_type = key)
                #根据id获取问题类型的一个对象
        
                question_list = sample(list(question_obj.question_set.all()),int(info[0]),)
                #用sample方法随机生成info[1](多少数量)个问题的列表
                
                info_dict[question_obj.question_type] = info[:]
                info_dict[question_obj.question_type].append(question_list)
                
        return info_dict
    # @property
    def info_dict_pk(self):
        save_info_dict = {}
        for key,value in self.info_dict.items():
            save_info_dict[key] = value[:]
            save_info_dict[key][2] = [i.id for i in self.info_dict[key][2]]  #获取问题id生成列表（为了保存数据库）
        return save_info_dict
          


        
      
